//自己的通用数组类
#pragma once
#include <iostream>
using namespace std;

template<class T>
class MyArray
{
private:
    T* pAddress; //指针指向堆区开辟的真实数组

    int capacity;

    int size;

public:
    //有参构造  
    MyArray(int capacity)
    {
        cout << "MyArray 有参构造调用" << endl;
        this->capacity = capacity;
        this->size = size;
        this->pAddress = new T[this->capacity];
    }

    //拷贝构造
    MyArray(const MyArray& arr)
    {
        cout << "MyArray 拷贝构造调用" << endl;
        this->capacity = arr.capacity;
        this->size = arr.size;
        //this->pAddress = arr->pAddress;

        //深拷贝
        this->pAddress = new T[arr.capacity];
        //将arr中的数据都拷贝过来
        for (int i = 0;i < this->capacity;i++)
        {
            this->pAddress[i] = arr.pAddress[i];
        }
    }

    //operator= 防止浅拷贝问题
    MyArray& operator=(const MyArray& arr)
    {
        cout << "MyArray operator=()调用" << endl;
        //先判断原来堆区是否有数据，如果有，先释放
        if (this->pAddress != NULL)
        {
            this->pAddress = NULL;
            this->capacity = 0;
            this->size = 0;
        }

        //深拷贝
        this->capacity = arr.capacity;
        this->size = arr.size;
        this->pAddress = new T[arr.capacity];

        //将arr中的数据都拷贝过来
        for (int i = 0;i < this->capacity;i++)
        {
            this->pAddress[i] = arr.pAddress[i];
        }

        return *this;
    }

    //尾插法
    void Push_Back(const T& val)
    {
        //判断是否可以插入
        if (this->capacity == this->size)
        {
            cout << "数组已满，无法插入！" << endl;
            return;
        }
        //尾插
        this->pAddress[this->size] = val;
        this->size++;
    }

    //尾删法
    void Pop_Back()
    {
        //判断是否可以删除
        if (this->size == 0)
        {
            cout << "数组为空，无法删除！" << endl;
        }
        
        this->size--;
    }

    //通过下标方式访问数组中的元素 
    T& operator[](int index)
    {
        return this->pAddress[index];
    }

    //返回数组容量
    int getCapacity()
    {
        return this->capacity;
    }

    //返回数组大小
    int getSize()
    {
        return this->size;
    }

    //析构函数
    ~MyArray()
    {
        cout << "MyArray 析构函数调用" << endl;
        if (this->pAddress != NULL)
        {
            this->pAddress = NULL;
        }
    }
};
